<template>
  <el-dialog :close-on-click-modal="false" :visible.sync="visible" top="0" :append-to-body="true" :lock-scroll="true"
    title="" class="img-preview" width="650px">
    <div class="img-box">
      <img :src="(imgUrl).indexOf('http')===-1 ? resourcesUrl + imgUrl : imgUrl" class="img">
    </div>
    <el-button @click="download((imgUrl).indexOf('http')===-1 ? resourcesUrl + imgUrl : imgUrl)" type="primary">点击下载<i
        class="el-icon-download el-icon--right"></i></el-button>
  </el-dialog>
</template>

<script>
  export default {

    data() {
      return {
        imgUrl: '',
        visible: false,
        resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
      }
    },

    methods: {
      download(img1) {
        // 创建图片元素
        var img = new Image();
        //设置图片跨域
        img.setAttribute("crossOrigin", "anonymous");
        //设置图片路径
        img.src = img1;
        //下载图片
        img.onload = function() {
            //创建画布
        	var can =  document.createElement("canvas");
            //设置画布大小
        	can.width=150;
        	can.height = 150;
        	let ctx = can.getContext("2d");
            //绘制图片
        	ctx.drawImage(img,0,0,150,150);
            //得到图片的base64编码数据
        	var newurl = can.toDataURL("image/png");
            // 生成一个a元素
        	var a = document.createElement("a");
            // 创建一个单击事件
        	var event = new MouseEvent("click");
            // 设置图片名称
        	a.download = "";
            // 将生成的URL设置为a.href属性
        	a.href = newurl;
            // 触发a的单击事件
        	a.dispatchEvent(event);
        }
      },
      init(imgUrl) {
       console.log(imgUrl)
        if(imgUrl == null || imgUrl == ''){
          this.$message.error('暂无该图片！！！')
        }else{
          this.imgUrl = imgUrl
          this.visible = true
        }
      }
    }

  }
</script>

<style lang="scss" scope>

  .img-preview.el-dialog__wrapper {
    display: flex;
    align-items: center;
  }

  .img-preview {

    // .el-dialog__headerbtn {
    //   top: 15px;
    // }
    .el-dialog__body {
      padding: 20px;
      padding-top: 10px;

      .img-box {
        display: block;
        width: 100%;
        max-height: 700px;
        overflow: auto;
      }

      .img-box::-webkit-scrollbar {
        display: none;
      }

      .img {
        display: block;
        width: 100%;
        height: auto;
      }
    }
  }
  .slide-enter-active, .slide-leave-active {
  transition: all 0.5s ease;
}
.slide-enter, .slide-leave-to {
  transform: translateY(-100%);
  opacity: 0;
}
</style>
